package midway.madness.post.article;

import midway.madness.R;
import midway.madness.utils.SplashScreen;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.webkit.WebView;

public class ArticleActivity extends Activity {

  private ArticleStateSaver saver;
  private String date, title, text, author, commentString;
  private SplashScreen splash;
  private WebView wv;

  public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	splash = new SplashScreen(ArticleActivity.this);
	splash.showSplash();

	setContentView(R.layout.article_web_view);
	wv = (WebView) findViewById(R.id.article_web_view);
	wv.getSettings().setUseWideViewPort(true);
	wv.setHorizontalScrollBarEnabled(true);
	wv.getSettings().setBuiltInZoomControls(true);

	new ArticleTask().execute(new Void[0]);
  }

  public Object onRetainNonConfigurationInstance() {
	ArticleStateSaver saver = new ArticleStateSaver();

	saver.setAuthor(author);
	saver.setComments(commentString);
	saver.setDate(date);
	saver.setText(text);
	saver.setTitle(title);

	return saver;
  }

  private class ArticleTask extends AsyncTask<Void, Void, Void> {

	@Override
	protected Void doInBackground(Void... arg0) {
	  saver = (ArticleStateSaver) getLastNonConfigurationInstance();
	  
	  String[] comments = null;

	  if (null != saver) {
		date = saver.getDate();
		title = saver.getTitle();
		text = saver.getText();
		author = saver.getAuthor();
		commentString = saver.getComments();
	  } else {
		Intent pastIntent = ArticleActivity.this.getIntent();
		date = pastIntent.getStringExtra("date");
		title = pastIntent.getStringExtra("title");
		text = pastIntent.getStringExtra("content");
		author = pastIntent.getStringExtra("author");
		comments = pastIntent.getStringArrayExtra("comments");
	  }

	  if (null == commentString){
		StringBuilder sb = new StringBuilder("");
		if (comments.length == 0) {
		  sb.append("\n\n <b>No Comments</b>");
		} else {
		  sb.append("\n\n <b><u>Comments</u></b> \n\n");
		}
		for (int i = 0; i < comments.length; i++) {
		  String[] temp = comments[i].split("->");
		  sb.append("<br /><br /><b>" + temp[0] + " " + temp[1] + "</b>");
		  sb.append(":\n");
		  sb.append(temp[2]);
		  if (i != comments.length - 1) {
			sb.append("\n\n");
		  }
		}
		commentString = sb.toString();
	  }

	  return null;
	}

	protected void onPostExecute(Void v) {
	  StringBuilder sb = new StringBuilder("");
	  sb.append("<h3>" + title + "</h3>");
	  sb.append(date + " BY " + author.toUpperCase());
	  sb.append("<br /><br />");
	  sb.append(text);
	  sb.append(commentString);
	  wv.loadDataWithBaseURL(null, sb.toString(), "text/html", "UTF-8", "");

	  splash.removeSplash();
	}
  }

}
